﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CsvHelper.cs" company="Collaboris Ltd.">
//   Copyright (c) Collaboris Ltd. All rights Reserved.
// </copyright>
// <summary>
//   Defines the CsvHelper type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Collaboris.Utils
{
    using System.IO;
    using System.Data;

    public static class CsvHelper
    {
        public static DataSet GetDataSetFromCSV(string filePath, string dataTableName)
        {
            string strLine;
            string[] strArray;
            char[] charArray = new char[] { ',' };
            DataSet ds = new DataSet();
            DataTable dt = ds.Tables.Add(dataTableName);
            FileStream aFile = new FileStream(filePath, FileMode.Open);
            StreamReader sr = new StreamReader(aFile);

            strLine = sr.ReadLine();

            strArray = strLine.Split(charArray);

            for (int x = 0; x <= strArray.GetUpperBound(0); x++)
            {
                dt.Columns.Add(strArray[x].Trim());
            }

            strLine = sr.ReadLine();
            while (strLine != null)
            {
                strArray = strLine.Split(charArray);
                DataRow dr = dt.NewRow();
                for (int i = 0; i <= strArray.GetUpperBound(0); i++)
                {
                    dr[i] = strArray[i].Trim();
                }
                dt.Rows.Add(dr);
                strLine = sr.ReadLine();
            }
            sr.Close();
            return ds;
        }
    }
}
